﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

namespace XxSystem.UsersServer.Ids4Svr
{
    public class MyProfileService : IProfileService
    {
        private readonly UserManager<ApplicationUser> _userManager;

        public MyProfileService(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }
        public async Task<List<Claim>> GetClaimsFromUserAsync(ApplicationUser user)
        {
            var claims = new List<Claim> {
                new Claim(JwtClaimTypes.Subject,user.Id.ToString()),
                new Claim(JwtClaimTypes.Name,user.NormalizedUserName),
                new Claim(JwtClaimTypes.PreferredUserName,user.UserName)
            };

            //var role = await _userManager.GetRolesAsync(user);
            //role.ToList().ForEach(f =>
            //{
            //    claims.Add(new Claim(JwtClaimTypes.Role, f));
            //});

            //if (!string.IsNullOrEmpty(user.Avatar))
            //{
            //    claims.Add(new Claim("avatar", user.Avatar));
            //}
            //claims.Add(new Claim("姓名", "tom"));
            return claims;
        }
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var subjectId = context.Subject?.Claims?.FirstOrDefault(c => c.Type == "sub")?.Value;
            var user = await _userManager.FindByIdAsync(subjectId);
            context.IssuedClaims = await GetClaimsFromUserAsync(user);
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var subjectId = context.Subject?.Claims?.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject)?.Value;
            var user = await _userManager.FindByIdAsync(subjectId);
            context.IsActive = user != null; //该用户是否已经激活，可用，否则不能接受token

            /*
             这样还应该判断用户是否已经锁定，那么应该IsActive=false
             */
        }
    }
}
